package com.wrt.sps.mgt.service.impl;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wrt.sps.mgt.dao.PermissionDao;
import com.wrt.sps.mgt.entity.Permission;
import com.wrt.sps.mgt.service.PermissionService;

/**
 * 权限服务实现层
 * 
 * @author 文瑞涛
 * @date 2021年1月7日 上午11:38:18
 */
@Service
public class PermissionServiceImpl implements PermissionService {

	@Resource
	private PermissionDao permissionDao;

	@Override
	@PostConstruct
	@Transactional(rollbackFor = Exception.class)
	public void initPermissions() {
		long countPermission = permissionDao.count();
		Set<Permission> adminPermissions = new HashSet<>();
		adminPermissions.addAll(Permission.allPermissions());
		if (adminPermissions.size() != countPermission) {
			Set<Permission> savedPermissions = getAllPermissions();
			for (Permission permission : savedPermissions) {
				adminPermissions.removeIf(t -> t.getPermissionName().equals(permission.getPermissionName()));
			}
			permissionDao.saveAll(adminPermissions);
		}
	}

	@Override
	@Transactional(readOnly = true)
	public Set<Permission> getAllPermissions() {
		return new HashSet<>(permissionDao.findAll());
	}

	@Override
	@Transactional(readOnly = true)
	public Set<Permission> findPermissionsByIds(Long[] ids) {
		return new HashSet<>(permissionDao.findAllById(Arrays.asList(ids)));
	}

}
